/**
 * 查找树形结构的第一个叶子节点
 * @param {Array} data 树形数据
 * @param {Object} options 配置选项
 * @returns {Object} 叶子节点信息
 */
export function findLeafNodes(data, options = {}) {
    const {
        childrenKey = 'children',
        nodeKey = 'node',
        idKey = 'id'
    } = options;

    if (!data || data.length === 0) {
        return { nodeId: '', node: null };
    }

    let current = data[0];
    const path = [current]; // 记录路径
    
    while (current && current[childrenKey] && current[childrenKey].length > 0) {
        current = current[childrenKey][0];
        path.push(current);
    }

    // 获取节点ID
    let nodeId = '';
    if (current && current[nodeKey]) {
        nodeId = current[nodeKey][idKey] || '';
    } else if (current && current[idKey]) {
        nodeId = current[idKey];
    }

    return {
        nodeId,
        node: current,
        path, // 返回路径信息
        isLeaf: !current || !current[childrenKey] || current[childrenKey].length === 0
    };
}

/**
 * 查找所有叶子节点
 * @param {Array} data 树形数据
 * @param {Array} result 结果数组
 * @returns {Array} 所有叶子节点
 */
export function findAllLeafNodes(data, result = []) {
    if (!data || !Array.isArray(data)) return result;
    
    data.forEach(item => {
        if (!item.children || item.children.length === 0) {
            result.push(item);
        } else {
            findAllLeafNodes(item.children, result);
        }
    });
    
    return result;
}

/**
 * 根据ID查找节点
 * @param {Array} data 树形数据
 * @param {string|number} id 要查找的ID
 * @returns {Object|null} 找到的节点
 */
export function findNodeById(data, id) {
    if (!data || !Array.isArray(data)) return null;
    
    for (const item of data) {
        if (item.node?.id === id || item.id === id) {
            return item;
        }
        if (item.children) {
            const found = findNodeById(item.children, id);
            if (found) return found;
        }
    }
    return null;
}

/**
 * 扁平化树形结构
 * @param {Array} data 树形数据
 * @returns {Array} 扁平化后的数组
 */
export function flattenTree(data) {
    const result = [];
    
    function traverse(nodes) {
        nodes.forEach(node => {
            result.push(node);
            if (node.children && node.children.length > 0) {
                traverse(node.children);
            }
        });
    }
    
    if (data && data.length > 0) {
        traverse(data);
    }
    
    return result;
}